﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MidnightPeach.Properties;

namespace MidnightPeach.Components
{
    public class RecentPackageList : IEnumerable<string>
    {
        private const int MaxItems = 10;

        #region singleton

        private static RecentPackageList _instance;

        public static RecentPackageList Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new RecentPackageList();
                return _instance;
            }
        }

        private RecentPackageList()
        {
            var items = Settings.Default.RecentPackageList.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries);

            _list = items.Where(x => string.IsNullOrEmpty(x) == false).ToList();
        }

        #endregion

        private readonly List<string> _list = new List<string>();

        public void Save()
        {
            string line = string.Join("|", _list.ToArray());
            Settings.Default.RecentPackageList = line;

            Settings.Default.Save();
        }

        public IEnumerator<string> GetEnumerator()
        {
            return ((IEnumerable<string>) _list).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void InsertAtZero(string filePath)
        {
            if (_list.Contains(filePath))
                return;

            _list.Insert(0, filePath);

            if (_list.Count > MaxItems)
                _list.RemoveAt(_list.Count - 1);
        }
    }
}
